<template>
  <a-modal
    title="簽約"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    footer=''
  >
    <a-spin :spinning="confirmLoading">
      <a-steps :current="current">
          <a-step v-for="item in steps" :key="item.title" :title="item.title"/>
      </a-steps>
      <div class="steps-content">
        <a-form :form="form">
          <div v-show="current === 0">
             <a-divider style="margin:6px 0px"/>
            <a-divider type="vertical" class="divider-only"/>租客信息
            <a-form-item v-show="false"><a-input v-decorator="['roomId', {rules: [{required: true, message: '请選擇入住房間！'}]}]" /></a-form-item>
             <a-form-item v-show="false"><a-input v-decorator="['ydType', { initialValue: 1 }]" /></a-form-item>
             <a-form-item v-show="false"><a-input v-decorator="['reservationId']" /></a-form-item>
             <a-form-item
              label="姓名"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入承租人姓名" v-decorator="['name', {rules: [{required: true, message: '请输入承租人姓名！'}]}]" />
            </a-form-item>
            <a-form-item
              label="聯係方式"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入聯係方式" v-decorator="['phone', {rules: [{required: true, message: '请输入聯係方式！'}]}]" />
            </a-form-item>
            <a-form-item
              label="身份证号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入身份证号" v-decorator="['idCard', {rules: [{required: true, message: '请输入身份证号！'}]}]" />
            </a-form-item>
            <a-form-item
              label="身份証照片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-row>
                <a-col :span="12" >
                  <a-input v-show="false" v-decorator="['idCardImagesFront']" />
                  <a-upload
                    :customRequest="customRequest1"
                    :multiple="false"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    name="file">
                    <a-button><a-icon type="upload"/>上傳正面照片</a-button>
                  </a-upload>
                  <a-spin :spinning="divLoading1">
                    <div>
                      <img :src="src1" @click="$refs.previewForm.preview(src1)" style="max-width: 99%;width:100px">
                    </div>
                  </a-spin>
                </a-col>
                <a-col :span="12">
                  <a-input v-show="false" v-decorator="['idCardImagesBack']" />
                  <a-upload
                    :customRequest="customRequest2"
                    :multiple="false"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    name="file">
                    <a-button><a-icon type="upload"/>上傳反面照片</a-button>
                  </a-upload>
                   <a-spin :spinning="divLoading2">
                    <div>
                      <img :src="src2" @click="$refs.previewForm.preview(src2)"style="max-width: 99%;width:100px">
                    </div>
                  </a-spin>
                </a-col>
              </a-row>
            </a-form-item>
            <a-divider type="vertical" class="divider-only"/>同住人
              <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="同住人"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columns"
                                :dataSource="leaseLiveData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="idCardImagesFront" slot-scope="text,record">
                                <div>
                                  <img :src="record.src1" @click="$refs.previewForm.preview(record.src1)" style="max-width: 99%;width:100px">
                                </div>
                              </template>
                               <template slot="idCardImagesBack" slot-scope="text,record">
                                <div>
                                  <img :src="record.src2" @click="$refs.previewForm.preview(record.src2)"   style="max-width: 99%;width:100px">
                                </div>
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="remove(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                <a-col :span="4">
                  <a-button type="primary" size="small" @click="addYj()" >添加同住人</a-button>
                </a-col>
              </a-row>
              <a-form-item
                label="入住房間"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
              <a-input  placeholder="入住房間" :disabled="true"  v-decorator="['roomName', {rules: [{ required: true, message: '請選擇入住房間！' }]}]">
                <a-icon slot="addonAfter" v-if="this.type === 1" type="search" @click="onSelectRoom"/>
                <!-- <a-icon slot="addonAfter" v-if="this.type === 2" type="search"/> -->
              </a-input>
              </a-form-item>
              <div>
                <a-form-item
                label="租期"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-date-picker
                  v-model="startValue"
                  :disabled-date="disabledStartDate"
                  format="YYYY-MM-DD"
                  placeholder="開始時間"
                  @openChange="handleStartOpenChange"
                />
                <a-date-picker
                  v-model="endValue"
                  :disabled-date="disabledEndDate"
                  format="YYYY-MM-DD"
                  placeholder="結束時間"
                  :open="endOpen"
                  @openChange="handleEndOpenChange"
                />
                <a-button style="margin-left: 10px;" type="dashed" size="small" :class="mocheck === 1 ? 'mocheck' : ''" @click="getEndTimeByStartTime(1)">三个月</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 2 ? 'mocheck' : ''" @click="getEndTimeByStartTime(2)">半年</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 3 ? 'mocheck' : ''" @click="getEndTimeByStartTime(3)">一年</a-button>
                <a-button  type="dashed" size="small" :class="mocheck === 4 ? 'mocheck' : ''" @click="getEndTimeByStartTime(4)">两年</a-button>
                </a-form-item>
              </div>
              <a-row :gutter="24">
              <a-form-item
              label="收租周期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input-group compact>
                <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptFu', { initialValue: 1, rules: [{ required: true, message: '请选择付款方式！' }]}]">
                    <a-select-option v-for="(item,index) in 18" :key="index" :value="item">付{{ item }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptYa', { initialValue: 1, rules: [{ required: true, message: '请选择押金方式！' }]}]" @change="onReceiptyaChange">
                    <a-select-option v-for="(item,index) in 18" :key="index" :value="item">押{{ item }}</a-select-option>
                    <a-select-option :value="19">押金自定義</a-select-option>
                  </a-select>
                </a-form-item>
                 <a-form-item
                    label=""
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                  <a-select style="width: 150px" v-decorator="['receiptYj', { initialValue: 2, rules: [{ required: true, message: '请选择付款周期！' }]}]">
                    <a-select-option :value="1">日</a-select-option>
                    <a-select-option :value="2">月</a-select-option>
                    <a-select-option :value="3">年</a-select-option>
                  </a-select>
                </a-form-item>
              </a-input-group>
            </a-form-item>
            </a-row>
            <a-form-item
              label="租金"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input-number
              style="width:100%"
              placeholder="請輸入租金"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['rent', { initialValue: 0, rules: [{required: true, message: '請輸入租金'}]}]"
              @change="onRentChange"/>
            </a-form-item>
            <a-form-item
              label="房屋押金"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input-number
              style="width:100%"
              placeholder="請輸入房屋押金"
              :precision="2"
              :min="0"
              :max="99999999"
              :step="10"
              v-decorator="['deposit', { initialValue: 0, rules: [{required: true, message: '請輸入房屋押金'}]}]"/>
            </a-form-item>
            <a-form-item
                label="賬單起始日"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-select style="width: 100%" placeholder="请选择賬單起始日" v-decorator="['billStart', { initialValue: 0 }]">
                      <a-select-option :key="0" :value="0">起租日</a-select-option>
                      <a-select-option v-for="(item,index) in 31" :key="index" :value="item">{{ item }}号</a-select-option>
                  </a-select>
            </a-form-item>
            <a-form-item
                  label="收租日"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-radio-group placeholder="请选择收租日" @change="onBillEndTypeChange" v-decorator="['billEndType', { initialValue: 0 }]">
                    <a-radio :style="radioStyle" :key="0" :value="0">提前</a-radio>
                    <div>
                      <a-form-item label="">
                        <a-input-number
                        :min="1"
                        :max="365"
                        :disabled="billEndTqDataable"
                        style="width:100%"
                        placeholder="请输入账单收租日提前几日"
                        v-decorator="['billEndTqData', { initialValue: 15 }]"/>
                        相较账单起始日提前几天
                      </a-form-item>
                    </div>
                    <a-radio :style="radioStyle" :key="1" :value="1">固定</a-radio>
                    <div  style="width: 100%">
                      <a-form-item  label="">
                        <a-select :disabled="billEndGdmonthDataDataable"  placeholder="请选择账单收租日固定几月" style="width: 100%" v-decorator="['billEndGdmonthData', { initialValue: 0 }]">
                          <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGdmonthDataData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>
                      <a-form-item >
                        <a-select :disabled="billEndGdmonthDataDataable"   placeholder="请选择账单收租日固定几日" style="width: 100%" v-decorator="['billEndGddayData', { initialValue: 5 }]">
                          <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGddayDataData" :key="index" :value="item">{{ item }}號</a-select-option>
                        </a-select>
                      </a-form-item>
                    </div>
                  </a-radio-group>
            </a-form-item>
          </div>
          <div v-show="current === 1">
             <a-divider style="margin:6px 0px"/>
                <a-divider type="vertical" class="divider-only"/>其他押金
              <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="其他押金"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columnsYj"
                                :dataSource="yjData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="amount" slot-scope="text, record">
                                <a-input-number
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleYjChange(e,record.key, 'amount')"
                                    :step="10"/>
                              </template>
                              <template slot="quantity" slot-scope="text, record">
                                <a-input-number
                                    v-if="record.deposittype === 1 || record.deposittype === '1'"
                                    style="width:100%"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleYjChange(e,record.key,'quantity')"
                                    :step="1"/>
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="removeYj(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                  <a-col :span="4">
                    <a-button type="primary" size="small" @click="addYjdd()" >添加押金</a-button>
                  </a-col>
              </a-row>
               <a-divider/>
              <a-divider type="vertical" class="divider-only"/>水電物業
              <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="水電物業"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columnsFy"
                                :dataSource="fyData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="amount" slot-scope="text, record">
                                <a-input-number
                                    style="width:100%"
                                    :disabled="record.type === '3' || record.type === 3"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'amount')"
                                    :step="10"/>
                              </template>
                              <template slot="solder" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'solder')"
                                    :step="10"/>
                              </template>
                              <template slot="magnification" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'magnification')"
                                    :step="10"/>
                              </template>
                              <template slot="patchlossrate" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'patchlossrate')"
                                    :step="10"/>
                              </template>
                              <template slot="initialreading" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'initialreading')"
                                    :step="10"/>
                              </template>
                              <template slot="ydzd" slot-scope="text, record">
                                <span  v-if="record.type !== '2' && record.type !== 2">
                                  <a-checkbox :default-checked="record.ydzd === 1" :disabled="!hydropowerChangeflg" @change="e => handleFyChange(e,record.key,'ydzd')">
                                    移到租金賬單
                                  </a-checkbox>
                                </span>
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="removeFy(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                <a-col :span="4">
                  <a-button type="primary" size="small" @click="addFy()" >添加費用</a-button>
                </a-col>
              </a-row>
              <a-form-item
                label="租金水電分開收取"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                >
                    <a-radio-group placeholder="请选择租金水電分開收取" button-style="solid" onch v-decorator="['hydropower',{ initialValue: 0, rules: [{ required: true, message: '请选择租金水電分開收取！' }]}]" @change="onHydropowerChange">
                      <a-radio-button  :key="0" :value="0">關閉</a-radio-button>
                      <a-radio-button  :key="1" :value="1">開啓</a-radio-button>
                    </a-radio-group>
              </a-form-item>
              <div class="fy-item" v-if="hydropowerChangeflg">
                <a-form-item
                  label="水電周期"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-select  style="width: 100%" placeholder="请选择水電周期" v-decorator="['hydropowercycle', { initialValue: 1 }]">
                        <a-select-option v-for="(item,index) in 18" :key="index" :value="item">{{ item }}月</a-select-option>
                    </a-select>
                  </a-form-item>
                <a-form-item
                  label="賬單起始日"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-select style="width: 100%" placeholder="请选择賬單起始日" v-decorator="['hydropowerBillStart', { initialValue: 0 }]">
                        <a-select-option :key="0" :value="0">起租日</a-select-option>
                        <a-select-option v-for="(item,index) in 31" :key="index" :value="item">{{ item }}号</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    label="收租日"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-radio-group placeholder="请选择收租日" @change="onHydropowerBillEndTypeChange" v-decorator="['hydropowerBillEndType', { initialValue: 0 }]">
                      <a-radio :style="radioStyle" :key="0" :value="0">提前</a-radio>
                      <div>
                        <a-form-item label="">
                          <a-input-number
                          :min="1"
                          :max="365"
                          :disabled="hydropowerBillEndTqDataable"
                          style="width:100%"
                          placeholder="请输入账单收租日提前几日"
                          v-decorator="['hydropowerBillEndTqData', { initialValue: 15 }]"/>
                          相较账单起始日提前几天
                        </a-form-item>
                      </div>
                      <a-radio :style="radioStyle" :key="1" :value="1">固定</a-radio>
                      <div  style="width: 100%">
                        <a-form-item  label="">
                          <a-select :disabled="hydropowerBillEndGdmonthDataDataable"  placeholder="请选择账单收租日固定几月" style="width: 100%" v-decorator="['hydropowerBillEndGdmonthData', { initialValue: 0 }]">
                            <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGdmonthDataData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                          </a-select>
                        </a-form-item>
                        <a-form-item >
                          <a-select :disabled="hydropowerBillEndGdmonthDataDataable"   placeholder="请选择账单收租日固定几日" style="width: 100%" v-decorator="['hydropowerBillEndGddayData', { initialValue: 5 }]">
                            <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGddayDataData" :key="index" :value="item">{{ item }}號</a-select-option>
                          </a-select>
                        </a-form-item>
                      </div>
                    </a-radio-group>
                  </a-form-item>
              </div>
              <a-divider/>
              <a-divider type="vertical" class="divider-only"/>家私配置
              <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="家私配置"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columnsJs"
                                :dataSource="jsData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="price" slot-scope="text, record">
                                    <a-input-number
                                      :min="0"
                                      :max="9999999"
                                      :value="text"
                                      :precision='2'
                                      :step="1"
                                      @change="e => handleChangeJs(e,record.key,'price')" />
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="removeJs(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                  <a-col :span="4">
                    <a-button type="primary" size="small" @click="addJs()" >添加家私</a-button>
                  </a-col>
              </a-row>
              <a-divider type="vertical" class="divider-only"/>其他信息
               <a-form-item
                label="收租提醒"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                >
                    <a-radio-group placeholder="请选择收租提醒" button-style="solid" onch v-decorator="['rentReminderSwitch',{ initialValue: 1, rules: [{ required: true, message: '请选择收租提醒！' }]}]" @change="onRentReminderSwitchChange">
                      <a-radio-button  :key="0" :value="0">關閉</a-radio-button>
                      <a-radio-button  :key="1" :value="1">開啓</a-radio-button>
                    </a-radio-group>
              </a-form-item>
              <div v-show="onRentReminderSwitch">
                 <a-form-item
                  label="收租提醒提前 天"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select  style="width: 100%" v-decorator="['rentReminderDay', { initialValue: 1 , rules: [{ required: true, message: '请选择收租提醒提前 天！' }]}]">
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 100" :key="index" :value="item">{{ item }}天</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="收租提醒提前 小時"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-select  style="width: 100%" v-decorator="['rentReminderHour', { initialValue: 0 , rules: [{ required: true, message: '请选择收租提醒提前 小時！' }]}]">
                    <a-select-option  style="width: 100%"   :key="0" :value="0">0點</a-select-option>
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 23" :key="index" :value="item">{{ item }}點</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="收租提醒提前 分鐘"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol">
                  <a-select  style="width: 100%" v-decorator="['rentReminderMinutes', { initialValue: 0 , rules: [{ required: true, message: '请选择收租提醒提前 分鐘！' }]}]">
                    <a-select-option  style="width: 100%"  :key="0" :value="0">0分</a-select-option>
                    <a-select-option  style="width: 100%"  v-for="(item,index) in 59" :key="index" :value="item">{{ item }}分</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="备注"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  has-feedback
                >
                  <a-textarea placeholder="请输入備注" v-decorator="['remark']" />
                </a-form-item>
              </div>
          </div>
        </a-form>
      </div>
      <div class="steps-action">
        <a-row type="flex" justify="center" align="top">
          <a-col :span="24">
            <a-button v-if="current === 0" class="stem-class" type="primary" @click="next">下一步</a-button>
            <a-button v-if="current === 0" class="stem-class" @click="handleCancel">取消</a-button>
            <a-button
              v-if="current === 1"
              type="primary"
              class="stem-class"
              @click="handleSubmit">保存</a-button>
              <a-button v-if="current === 1" class="stem-class" style="margin-left: 8px" @click="prev">上一步</a-button>
              <a-button v-if="current === 1" class="stem-class" @click="handleCancel">取消</a-button>
          </a-col>
        </a-row>
      </div>
    </a-spin>
    <add-live-form ref="addLiveForm" @ok="handleOk"/>
    <room-num-select ref="roomNumSelect" @ok="handleSelectRoomOk" />
    <add-yj-form ref="addYjForm" @ok="yjhandleOk" />
    <add-expenses-form ref="addExpensesForm" @ok="fyhandleOk" />
    <add-furniture-form ref="addFurnitureForm" @ok="jshandleOk" />
    <preview-form ref="previewForm" />
  </a-modal>
</template>
<script>
  import moment from 'moment'
  import { houseLeaseAdd } from '@/api/modular/main/houselease/houseLeaseManage'
  import { sysFileInfoUpload, sysFileInfoPreview } from '@/api/modular/system/fileManage'
  import { busRoomById } from '@/api/modular/main/busroom/busRoomManage'
  import { getDepositListByRoomId } from '@/api/modular/main/roomdeposit/roomDepositManage'
  import { getRoomFurnitureListByRoomId } from '@/api/modular/main/roomfurniture/roomFurnitureManage'
  import { getExpensesListByRoomId } from '@/api/modular/main/roomexpenses/roomExpensesManage'
  import addLiveForm from './addLiveForm.vue'
  import roomNumSelect from '../roomreservation/roomNumSelect.vue'
  import addYjForm from '../busrealestate/addYjForm.vue'
  import addExpensesForm from '../busrealestate/addExpensesForm.vue'
  import addFurnitureForm from '../busrealestate/addFurnitureForm.vue'
  import previewForm from './previewForm'
  export default {
    components: {
      addLiveForm,
      roomNumSelect,
      addYjForm,
      addExpensesForm,
      addFurnitureForm,
      previewForm
    },
    data () {
      return {
        current: 0,
        type: 1,
        steps: [
          {
            title: '第一步:租約信息',
            content: 1
          },
          {
            title: '第二步:費用信息',
            content: 2
          }
        ],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
         // 机构行样式
        labelCol_JG: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol_JG: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        rentStartDateDateString: '',
        rentEndDateDateString: '',
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        memberLoading: false,
        src1: '',
        divLoading1: false,
        src2: '',
        divLoading2: false,
        columns: [
          {
            title: '姓名',
            dataIndex: 'name',
            width: '15%',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '手機號',
            dataIndex: 'phone',
            width: '20%',
            scopedSlots: { customRender: 'phone' }
          },
          {
            title: '身份證號',
            dataIndex: 'idCard',
            width: '25%',
            scopedSlots: { customRender: 'idCard' }
          },
           {
            title: '照片正面',
            dataIndex: 'idCardImagesFront',
            width: '15%',
            scopedSlots: { customRender: 'idCardImagesFront' }
          },
          {
            title: '照片反面',
            dataIndex: 'idCardImagesBack',
            width: '15%',
            scopedSlots: { customRender: 'idCardImagesBack' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        // 同住人數據
        leaseLiveData: [],
        startValue: null,
        endValue: null,
        endOpen: false,
        radioStyle: {
          display: 'block',
          height: '30px',
          lineHeight: '30px'
        },
        billEndGdmonthDataData: [ { 'code': 12, 'name': '提前12月' }, { 'code': 11, 'name': '提前11月' }, { 'code': 10, 'name': '提前10月' }, { 'code': 9, 'name': '提前9月' }, { 'code': 8, 'name': '提前8月' }, { 'code': 7, 'name': '提前7月' }, { 'code': 6, 'name': '提前6月' }, { 'code': 5, 'name': '提前5月' }, { 'code': 4, 'name': '提前4月' }, { 'code': 3, 'name': '提前3月' }, { 'code': 2, 'name': '提前2月' }, { 'code': 1, 'name': '提前1月' }, { 'code': 0, 'name': '当月' }, { 'code': -1, 'name': '延後1月' }, { 'code': -2, 'name': '延後2月' }, { 'code': -3, 'name': '延後3月' }, { 'code': -4, 'name': '延後4月' }, { 'code': -5, 'name': '延後5月' }, { 'code': -6, 'name': '延後6月' }, { 'code': -7, 'name': '延後7月' }, { 'code': -8, 'name': '延後8月' }, { 'code': -9, 'name': '延後9月' }, { 'code': -10, 'name': '延後10月' }, { 'code': -11, 'name': '延後11月' }, { 'code': -12, 'name': '延後12月' } ],
        billEndGddayDataData: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ],
        mocheck: 1,
        yjData: [],
        fyData: [],
        jsData: [],
        columnsYj: [
          {
            title: '押金名稱',
            dataIndex: 'depositname',
            width: '30%',
            scopedSlots: { customRender: 'depositname' }
          },
          {
            title: '金額',
            dataIndex: 'amount',
            width: '30%',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '數量',
            dataIndex: 'quantity',
            width: '30%',
            scopedSlots: { customRender: 'quantity' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        columnsJs: [
          {
            title: '家私名稱',
            dataIndex: 'name',
            width: '35%',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '數量',
            dataIndex: 'quantity',
            width: '15%',
            scopedSlots: { customRender: 'quantity' }
          },
          {
            title: '金額',
            dataIndex: 'price',
            width: '40%',
            scopedSlots: { customRender: 'price' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        columnsFy: [
          {
            title: '費用項',
            dataIndex: 'name',
            width: '15%',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '價格',
            dataIndex: 'amount',
            width: '10%',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '保底用量',
            dataIndex: 'solder',
            width: '15%',
            scopedSlots: { customRender: 'solder' }
          },
          {
            title: '倍率',
            dataIndex: 'magnification',
            width: '10%',
            scopedSlots: { customRender: 'magnification' }
          },
          {
            title: '表損率%',
            dataIndex: 'patchlossrate',
            width: '10%',
            scopedSlots: { customRender: 'patchlossrate' }
          },
          {
            title: '初始讀數',
            dataIndex: 'initialreading',
            width: '15%',
            scopedSlots: { customRender: 'initialreading' }
          },
          {
            title: '移到租金賬單',
            dataIndex: 'ydzd',
            width: '15%',
            scopedSlots: { customRender: 'ydzd' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        // 收租提醒开关
        onRentReminderSwitch: true,
        // 账单
        billEndGdmonthDataDataable: false,
        billEndTqDataable: false,
        // 水電物業租金水电分开收取標志
        hydropowerChangeflg: false,
        hydropowerBillEndTqDataable: false,
        hydropowerBillEndGdmonthDataDataable: false
      }
    },
    methods: {
      // 初始化方法
      add (type, record) {
        this.visible = true
        this.type = type
        if (type === 2) {
          setTimeout(() => {
            this.form.setFieldsValue(
              {
                ydType: type,
                reservationId: record.id,
                name: record.reservation,
                roomId: record.roomId,
                roomName: record.roomCode,
                phone: record.phone,
                idCard: record.idCard
              }
            )
          }, 100)
        }
        if (type === 3) {
          this.getRoomMsgById(record.roomId)
          setTimeout(() => {
            this.form.setFieldsValue(
              {
                roomId: record.roomId,
                roomName: record.roomCode
              }
            )
          }, 100)
        }
        this.startValue = moment().format('YYYY-MM-DD')
        this.onBillEndChange(0)
        this.getEndTimeByStartTime(this.mocheck)
      },
      getCurrentData() {
        return new Date().toLocaleDateString()
      },
      next() {
        var validateFieldsList = ['name', 'phone', 'idCard', 'roomId', 'roomName']
        this.form.validateFields(validateFieldsList, (errors, values) => {
          if (!errors) {
            this.current = 1
          }
        })
      },
      getYjData(roomId) {
        this.yjData = []
        getDepositListByRoomId(roomId).then((res) => {
          if (res.code === 200) {
            this.yjData = res.data
          } else {
            this.$message.error('查詢失敗')//  + res.message
          }
        })
      },
      getFyData(roomId) {
        this.fyData = []
        getExpensesListByRoomId(roomId).then((res) => {
          if (res.code === 200) {
            this.fyData = res.data
          } else {
            this.$message.error('查詢失敗')//  + res.message
          }
        })
      },
      getJsData(roomId) {
         this.jsData = []
        getRoomFurnitureListByRoomId(roomId).then((res) => {
          if (res.code === 200) {
            this.jsData = res.data
          } else {
            this.$message.error('查詢失敗')//  + res.message
          }
        })
      },
      prev() {
        this.current = 0
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('只允許上傳圖片!')
        }
        const isLt2M = file.size / 1024 / 1024 < 6
        if (!isLt2M) {
          this.$message.error('圖片大小不允許超過6MB!')
        }
        return isJpgOrPng && isLt2M
      },
       /**
       * 上传文件
       */
      customRequest1 (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.code === 200) {
            this.sysFileInfoPreview(res.data, '1')
            this.$nextTick(() => {
                this.form.setFieldsValue({
                  idCardImagesBack: res.data
                })
            })
          } else {
            this.$message.error('上传失败：' + res.msg)
          }
        })
      },
      customRequest2 (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.code === 200) {
            this.sysFileInfoPreview(res.data, '2')
            this.$nextTick(() => {
                this.form.setFieldsValue({
                  idCardImagesFront: res.data
                })
            })
          } else {
            this.$message.error('上传失败：' + res.msg)
          }
        })
      },
      /**
       * 获取图片并转为链接
       */
      sysFileInfoPreview (id, type) {
        sysFileInfoPreview({ id: id }).then((res) => {
          this.downloadfile(res, type)
        }).catch((err) => {
          this.$message.error('预览错误：' + err.message)
        })
      },
      /**
       * 转图片类型
       */
      downloadfile (res, type) {
        const blob = new Blob([res])
        if (type === '1') {
          this.src1 = window.URL.createObjectURL(blob)
        } else {
          this.src2 = window.URL.createObjectURL(blob)
        }
      },
      // 添加同住人
      addYj() {
          this.$refs.addLiveForm.add(this.leaseLiveData.length)
      },
      /**
       * 删除
       */
      remove (key) {
        const newData = this.leaseLiveData.filter(item => item.key !== key)
        this.leaseLiveData = newData
      },
      handleOk(values) {
        this.leaseLiveData.push(values)
      },
      onSelectRoom() {
        this.$refs.roomNumSelect.select(1)
      },
      handleSelectRoomOk (roomId, roomStrName) {
        this.getRoomMsgById(roomId)
        this.$nextTick(() => {
            this.form.setFieldsValue({
              roomId: roomId,
              roomName: roomStrName
            })
        })
      },
      // 初始化
      chengeYdzdType(value) {
        if (value === 0) {
          this.hydropowerChangeflg = false
        } else {
          this.hydropowerChangeflg = true
        }
      },
      getRoomMsgById(id) {
        this.getYjData(id)
        this.getFyData(id)
        this.getJsData(id)
        busRoomById({ id: id }).then((res) => {
              if (res.code === 200) {
                 setTimeout(() => {
                  this.form.setFieldsValue({
                      receiptFu: res.data.receiptfu,
                      receiptYa: res.data.receiptya,
                      receiptYj: res.data.receiptyj,
                      rent: res.data.rent,
                      deposit: res.data.deposit,
                      hydropower: res.data.hydropower,
                      hydropowercycle: res.data.hydropowercycle,
                      hydropowerBillStart: res.data.billstart,
                      hydropowerBillEndType: res.data.billEndType,
                      hydropowerBillEndTqData: res.data.billEndTqData,
                      hydropowerBillEndGdmonthData: res.data.billEndGdmonthData,
                      hydropowerBillEndGddayData: res.data.billEndGddayData
                  })
                }, 100)
                this.chengeYdzdType(res.data.hydropower)
                this.onsDBillEndChange(res.data.billEndType)
                if (res.data.billEndType) {
                  this.onsDBillEndChange(res.data.billEndType)
                } else {
                  this.onBillEndChange(0)
                }
              } else {
              }
            }).finally((res) => {
        })
      },
      onBillEndChange (e) {
        if (e === 0) {
          this.billEndTqDataable = false
          this.billEndGdmonthDataDataable = true
        } else {
          this.billEndTqDataable = true
          this.billEndGdmonthDataDataable = false
        }
      },
      onsDBillEndChange (e) {
        if (e === 0) {
          this.hydropowerBillEndTqDataable = false
          this.hydropowerBillEndGdmonthDataDataable = true
        } else {
          this.hydropowerBillEndTqDataable = true
          this.hydropowerBillEndGdmonthDataDataable = false
        }
      },
      disabledStartDate(startValue) {
        const endValue = this.endValue
        if (!startValue || !endValue) {
          return false
        }
        return startValue.valueOf() > endValue.valueOf()
      },
      disabledEndDate(endValue) {
        const startValue = this.startValue
        if (!endValue || !startValue) {
          return false
        }
        return startValue.valueOf() >= endValue.valueOf()
      },
      handleStartOpenChange(open) {
        if (!open) {
          this.endOpen = true
        }
      },
      handleEndOpenChange(open) {
        this.endOpen = open
      },
      // 租金点击事件
      onRentChange(value) {
        const receiptya = this.form.getFieldValue('receiptYa')
        if (receiptya === 19) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: value
            })
          })
        } else {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: value * receiptya
            })
          })
        }
      },
      // 押金点击事件
      onReceiptyaChange(value) {
        if (value !== 19) {
         const rent = this.form.getFieldValue('rent')
         const rentPrice = value * rent
          this.$nextTick(() => {
            this.form.setFieldsValue({
              deposit: rentPrice
            })
          })
        }
      },
      onBillEndTypeChange (e) {
        if (e.target.value === 0) {
          this.billEndTqDataable = false
          this.billEndGdmonthDataDataable = true
        } else {
          this.billEndTqDataable = true
          this.billEndGdmonthDataDataable = false
        }
      },
      onHydropowerBillEndTypeChange (e) {
        if (e.target.value === 0) {
          this.hydropowerBillEndTqDataable = false
          this.hydropowerBillEndGdmonthDataDataable = true
        } else {
          this.hydropowerBillEndTqDataable = true
          this.hydropowerBillEndGdmonthDataDataable = false
        }
      },
      getEndTimeByStartTime(type) {
        let month = 3
        if (type === 1) {
          month = 3
        } else if (type === 2) {
          month = 6
        } else if (type === 3) {
          month = 12
        } else if (type === 4) {
          month = 24
        }
        this.mocheck = type
        this.endValue = moment(this.startValue).add(month, 'months').subtract(1, 'days').format('YYYY-MM-DD')
      },
      onRentReminderSwitchChange() {
        this.onRentReminderSwitch = !this.onRentReminderSwitch
      },
      /**
       * 删除押金
       */
      removeYj (key) {
        const newData = this.yjData.filter(item => item.key !== key)
        this.yjData = newData
      },
      /**
       * 押金选择子表单单项触发
       */
      handleYjChange (value, key, column) {
        const newData = [...this.yjData]
        const target = newData.find(item => key === item.key)
        if (target) {
          target[column] = value
          this.yjData = newData
        }
      },
      // 添加押金
      addYjdd() {
        this.$refs.addYjForm.add(this.yjData)
      },
      yjhandleOk (param) {
        const selectedRowKeysYjlen = param.length
        if (selectedRowKeysYjlen > 0) {
           for (var i = 0; i < selectedRowKeysYjlen; i++) {
              var quantityNum = 0
              if (param[i].deposittype === '1') {
                quantityNum = 1
              }
              this.yjData.push({ key: param[i].key, disabled: true, depositname: param[i].depositname, depositid: param[i].depositid, deposittype: param[i].deposittype, amount: 0.00, quantity: quantityNum })
           }
        }
      },
       // 费用表
      addFy() {
        this.$refs.addExpensesForm.add(this.fyData)
      },
      handleFyChange (value, key, column) {
        if (column === 'ydzd') {
          var ydzd = 1
          if (!value.target.checked) {
            ydzd = 0
          }
          const newData = [...this.fyData]
          const target = newData.find(item => key === item.key)
          if (target) {
            target[column] = ydzd
            this.fyData = newData
          }
        } else {
          const newData = [...this.fyData]
          const target = newData.find(item => key === item.key)
          if (target) {
            target[column] = value
            this.fyData = newData
          }
        }
      },
      removeFy(key) {
        const newData = this.fyData.filter(item => item.key !== key)
        this.fyData = newData
      },
      // 费用确认回调
      fyhandleOk(param) {
        const selectedRowKeysYjlen = param.length
        if (selectedRowKeysYjlen > 0) {
           for (var i = 0; i < selectedRowKeysYjlen; i++) {
              this.fyData.push({ key: param[i].key, name: param[i].name, costid: param[i].costid, type: param[i].type, amount: 0.00, solder: 0, magnification: 1, patchlossrate: 0.00, initialreading: 0, ydzd: 1 })
           }
        }
      },
       // 水电物业分开收取开关
      onHydropowerChange(e) {
        if (e.target.value === 0) {
          this.hydropowerChangeflg = false
        } else {
          this.hydropowerChangeflg = true
        }
      },
      /**
       * 删除
       */
      removeJs (key) {
        const newData = this.jsData.filter(item => item.key !== key)
        this.jsData = newData
      },
      /**
       * 选择子表单单项触发
       */
      handleChangeJs (value, key, column) {
        const newData = [...this.jsData]
        const target = newData.find(item => key === item.key)
        if (target) {
          target[column] = value
          this.jsData = newData
        }
      },
      addJs() {
        this.$refs.addFurnitureForm.add(this.jsData)
      },
      jshandleOk(param) {
        const selectedRowKeysYjlen = param.length
        if (selectedRowKeysYjlen > 0) {
           for (var i = 0; i < selectedRowKeysYjlen; i++) {
              this.jsData.push({ key: 'NEW' + (this.jsData.length + 1), furnitureid: param[i].furnitureid, disabled: true, name: param[i].name, price: 0.00, quantity: 1 })
           }
        }
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        var validateFieldsList = []
        const receiptya = this.form.getFieldValue('rentReminderSwitch')
        if (receiptya === 1) {
          validateFieldsList.push('rentReminderDay')
          validateFieldsList.push('rentReminderHour')
          validateFieldsList.push('rentReminderMinutes')
        }
        validateFields(validateFieldsList, (errors, values) => {
          if (!errors) {
            if (!(this.startValue && this.endValue)) {
              this.$message.error('租期開始時間結束時間不允許爲空！')
              return false
            }
            if (this.startValue.valueOf() >= this.endValue.valueOf()) {
              this.$message.error('租期開始時間不允許大於結束時間！')
              return false
            }
          }
        })
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.billStart = 0
            values.rentStartDate = moment(this.startValue).format('YYYY-MM-DD')
            values.rentEndDate = moment(this.endValue).format('YYYY-MM-DD')
            values.leaseLiveData = this.leaseLiveData
            values.yjData = this.yjData
            values.fyData = this.fyData
            values.jsData = this.jsData
            houseLeaseAdd(values).then((res) => {
              if (res.code === 200) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.msg)// + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
             this.confirmLoading = false
          }
        })
      },
      onChangerentStartDate(date, dateString) {
        this.rentStartDateDateString = dateString
      },
      onChangerentEndDate(date, dateString) {
        this.rentEndDateDateString = dateString
      },
      handleCancel () {
        this.type = 1
        this.form.resetFields()
        this.visible = false
        this.startValue = null
        this.endValue = null
        this.endOpen = false
        this.current = 0
        this.leaseLiveData = []
        this.yjData = []
        this.fyData = []
        this.jsData = []
      }
    }
  }
</script>
<style scoped>
.stem-class{
    float: right;
}
.divider-only{
  background-color: aqua;
  width: 5px;
  height: 1.9em;
}
.divider-content-only{
  font-size: 20px;
  margin-bottom: 10px;
}
.divider-content-center-only{
  margin-top: 10px;
}
.mocheck{
  background-color: rgba(58, 136, 180, 0.822);
  color: aliceblue;
}
</style>
